<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row v-if="title === '批量填写计费单重'">
          <a-col :span="24">
            <a-form-model-item label="批量计费单重" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="chargeWeight">
              <a-input-number v-model="model.chargeWeight" placeholder="请输入批量计费单重" :precision="3" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row v-else>
          <a-col :span="24">
            <a-form-model-item label="重量段标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="title">
              <a-input v-model.trim="model.title" placeholder="请输入重量段标题"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="计费类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="chargeType">
              <j-dict-select-tag ref="chargeTypeRef" type="list" v-model="model.chargeType" dictCode="logistics_charge_type" placeholder="请选择计费类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="开始重量段" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="startWeight">
              <a-input-number v-model="model.startWeight" placeholder="请输入开始重量段" :precision="3" style="width: 100%" @change="validEndWeight_" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="结束重量段" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="endWeight">
              <a-input-number v-model="model.endWeight" placeholder="请输入结束重量段" :precision="3" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="最低计费重" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="minChargeWeight">
              <a-input-number v-model="model.minChargeWeight" placeholder="请输入计费单重（KG）" :precision="3" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="计费单重" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="chargeWeight">
              <a-input-number v-model="model.chargeWeight" placeholder="请输入计费单重（KG）" :precision="3" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import { httpAction, getAction, deleteAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'

export default {
  name: 'LogisticsWeightRangeDetailForm',
  components: {
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    title: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      model:{
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        title: [
          { required: true, message: '请输入重量段标题!'},
        ],
        chargeType: [
          { required: true, message: '请输入计费类型!'},
        ],
        startWeight: [
          { required: true, message: '请输入开始重量!'},
        ],
        endWeight: [
          { required: true, message: '请输入结束重量!' },
          { validator: this.validEndWeight }
        ],
        chargeWeight: [
          { required: true, message: '请输入计费单重!'},
        ]
      },
      url: {
        add: "/logistics/weightDetail/logisticsWeightRangeDetail/add",
        edit: "/logistics/weightDetail/logisticsWeightRangeDetail/edit",
        queryById: "/logistics/weightDetail/logisticsWeightRangeDetail/queryById",
        editChargeWeightBatch: "/logistics/weightDetail/logisticsWeightRangeDetail/editChargeWeightBatch"
      },
      selectedRowKeys: [],
      dataSource: []
    }
  },
  computed: {
    formDisabled(){
      return this.disabled
    },
  },
  created () {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model));
  },
  methods: {
    add (weightRangeId) {
      this.modelDefault.weightRangeId=weightRangeId;
      this.edit(this.modelDefault);
    },
    edit (record) {
      this.model = Object.assign({}, record);
      this.visible = true;
      if(!this.model.id){
        this.$nextTick(() => {
          if(this.$refs.chargeTypeRef){
            let dictOptions = this.$refs.chargeTypeRef.getCurrentDictOptions();
            this.$set(this.model, 'chargeType', (dictOptions && dictOptions[0] && dictOptions[0].value) || '');
          }
        })
      }
    },
    submitForm () {
      const that = this;
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid) {
          if(this.title === '批量填写计费单重'){
            let parmas = {
              chargeWeight: this.model.chargeWeight,
              ids: this.selectedRowKeys.join(',')
            }
            deleteAction(this.url.editChargeWeightBatch, parmas).then((res) => {
              if(res.success){
                this.$message.success('修改成功!');
                this.$emit('ok');
              }else{
                this.$message.warning(res.message);
              }
            })
            return;
          }
          //检测新增数据重量段是否已包含
          let flag = this.dataSource.some(item => {
            return (this.model.startWeight >= item.startWeight && this.model.startWeight <= item.endWeight) || (this.model.endWeight >= item.startWeight && this.model.endWeight <= item.endWeight);
          })
          if(flag){
            this.$message.warning('重量段范围数据已存在');
            return;
          }
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if(!this.model.id){
            httpurl+=this.url.add;
            method = 'post';
          }else{
            httpurl+=this.url.edit;
            method = 'put';
          }
          httpAction(httpurl,this.model,method).then((res)=>{
            if(res.success){
              that.$message.success(res.message);
              that.$emit('ok');
            }else{
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        }

      })
    },
    validEndWeight(rule,value,callback){
      if(this.model.startWeight > this.model.endWeight){
        callback("结束重量不可小于开始重量")
      }else{
        callback()
      }
    },
    validEndWeight_(){
      //清除校验
      if(this.model.startWeight <= this.model.endWeight){
        this.$refs.form.clearValidate(['endWeight'])
      }
    }
  }
}
</script>